# -*- coding: utf-8 -*-
import json
import urllib

import requests
from django.conf import settings
from django.utils.encoding import smart_unicode

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.crypt.CryptoHelper import CryptoHelper
from common.utils.exceptions import DataError, ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '301586521': {
        'appvkey': 'MIICXQIBAAKBgQCxWlDYbYAm9BN5fZWgYc2ZJjFeqVCnrbDMqGyYIoqkWZpmmusK7DxcB5oFl5IR2fBntjOSOwWPF4vxEd/YKU40Vc592XlHv9sVXpELNUKc9m3WdnOKblVtofoRW0vCaS5pCr7dw6PP/KtN46Etu9jA856IZC3t3umGuODFMsEw8QIDAQABAoGAfftkFnmiYQlclB6rnSQcgj/pLg8kJhhx0M+LZH6U8a5cyaoecMHjFpSnynUi499msKVy+NtIVZ8qX3KNCeY9kCqHf8Ovoum4+BtuN3dYC/sAydVgek2xFHAnNmfdUB3AT0CCvqKkqfizyDmUwc03GAJPXcF/vKgfjKMQ8ZhNtAECQQDxxRnT+Z/3qAppeDGLkpjstGlK1DgHgTe3m3DM9TXkE2+PlUP4jx6Z/4B/jYqKtRo+8Gdhhp/EuMcIITuQ8zNRAkEAu8qaA9otLhio2mzZD3RdzwjtHrhScdoxWwYcwuNSuw8im+odNiZoQ2qL0xAcSnZywS1lsCCiSukMfGZtqEZ7oQJBAMfWHQUjPeAcm46V9I3jPFfav3VEeJNrcTxoVRJ0VHkSv5G01RvsYGT11aaYvbzs+KaxWyI3fnPCL3E+1td2ziECQQC4x6RAgh/OqckME+qJQHFF1Hytq6TEDnReImeOhGvVUBE35WcU7znMjDxFVCbiRiaoWmkioxnOJ/53MbpYx/HBAkB93Lh4ufRmM0BEJC6mfHEODXma38Is0VEAw6cRx/XyphEyai81tPgRmaVhacsuyQUO8XfLadR1xKc6RP6Ui63g',
        'platpkey': 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvshfmRikZJBT5C7JYW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U3puSwcp3/wjbN+IqaaY27ZgqBf5TcgTiYK75keQ9p95Sgwm8tGrBW7sKsQscyx8xe11C0XO+FDmGGkEcQnJhog9waNYH0paIlbZZwaISAcm50eoPY8k0YKpkO4Ph8InLDeQIDAQAB'
    }
}


def _get_app_conf(app_id):
    return APP_CONF[app_id]


def create_charge(pay, pay_amount, info):
    """
    下单
    """
    charge_resp = {}
    app_id = info['app_id']
    app_conf = _get_app_conf(app_id)
    crypto = CryptoHelper()
    privateKey = CryptoHelper.importKey(app_conf["appvkey"])
    cp = CPOrder(app_conf['appvkey'], app_conf['platpkey'])
    url = "http://ipay.iapppay.com:9999/payapi/order"
    body = {
        "appid": app_id,
        "cporderid": str(pay.id),
        "currency": "RMB",
        "appuserid": "unknow",
        "waresname": u"优惠商品",
        "waresid": 1,
        "price": float(pay_amount),
        "cpprivateinfo": "unknow",
        "notifyurl": "{}/pay/api/{}/iapppay/".format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH),
    }
    result = cp.process_request(url, body)
    transid = json.loads(result['transdata']).get('transid')
    r_dict = {
        'tid': transid,
        'app': app_id,
        'url_r': '{}/pay/api/{}/iapppay/?pay_id={}'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id),
        'url_h': '{}/pay/api/{}/iapppay/?pay_id={}'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id),
    }
    data = json.dumps(r_dict, ensure_ascii=False).encode('utf8')
    req_sign = crypto.sign(data, privateKey)
    web_url = 'https://web.iapppay.com/pay/gateway?data={}&sign={}&sign_type=RSA'.format(
        urllib.quote(data), urllib.quote(req_sign))
    charge_resp.update({
        'charge_info': web_url
    })
    return charge_resp


def check_notify_sign(request):
    crypto = CryptoHelper()
    try:
        request_body = smart_unicode(urllib.unquote(request.body).decode('utf8'))
    except Exception as e:
        request_body = str(urllib.unquote(request.body).decode('utf8'))
    try:
        trans_data = crypto.fetch_transdata(request_body)
        data = json.loads(trans_data)
        app_id = data.get('appid')
        app_conf = _get_app_conf(app_id)
        platpkey = CryptoHelper.importKey(app_conf["platpkey"])
    except Exception as e:
        raise DataError('transdata {} invalid {}'.format(trans_data, e))
    result = crypto.segmentation_data(request_body, platpkey)
    if result:
        data = json.loads(result['transdata'])
        pay_id = data.get('cporderid')
        if not pay_id:
            _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
            raise ParamError('iapppay event does not contain pay ID')

        pay = order_db.get_pay(int(pay_id))
        if not pay:
            raise ParamError('pay_id: %s invalid' % pay_id)
        if pay.status != PAY_STATUS.READY:
            raise ParamError('pay %s has been processed' % pay_id)

        trade_status = int(data['result'])
        mch_id = pay.mch_id
        trade_no = data['transid']
        total_fee = data['money']

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        from common.channel.pay import check_channel_order
        check_channel_order(pay_id, total_fee, app_id)
        if trade_status == 0:
            _LOGGER.info('iapppay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
            order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
            # async notify
            async_job.notify_mch(pay_id)
    else:
        raise DataError('iapppay notify process error: %s', request_body)


def query_charge(pay_order, app_id):
    pass


class CPOrder:
    def __init__(self, appvkey, platpkey):
        self.crypto = CryptoHelper()
        self.privateKey = CryptoHelper.importKey(appvkey)
        self.platpkey = CryptoHelper.importKey(platpkey)

    def process_request(self, url, body):
        req_text = json.dumps(body, ensure_ascii=False).encode('utf8')
        req_sign = self.crypto.sign(req_text, self.privateKey)
        http_request_body = {
            'transdata': req_text,
            'sign': req_sign,
            'signtype': 'RSA'
        }
        text = requests.post(url, data=http_request_body, timeout=3)
        s = text.content
        reqData = urllib.unquote(str(s)).decode('utf8')
        return self.crypto.segmentation_data(smart_unicode(reqData), self.platpkey)


if __name__ == '__main__':
    cp = CPOrder()
    url = "http://ipay.iapppay.com:9999/payapi/order"
    body = {
        "appid": "3000000000",
        "cporderid": "55df2xge1c0dc98c7398231cd",
        "currency": "RMB",
        "appuserid": "dddddd",
        "waresname": "购买游戏币",
        "waresid": 1,
        "price": 1.00,
        "cpprivateinfo": "fd",
        "notifyurl": "www.baidu.com"}
    cp.process_request(url, body)
